<!-- 新增/编辑计量单位弹出框 -->
<template>
  <a-modal
    width="auto"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
  >
    <template #title>添加产品</template>
    <a-form auto-label-width :model="currForm.list" direction="vertical">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="物料编码：">
            <a-input v-model="currForm.list.number"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料名称：">
            <a-input v-model="currForm.list.name"></a-input>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="规格型号：">
            <a-input v-model="currForm.list.spec"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料分类：">
            <a-tree-select
              :data="classficationList"
              placeholder="请选择物料"
              allow-clear
              allow-search
              :filter-tree-node="filterClassficationData"
              v-model="currForm.list.materialId"
              :field-names="{
                key: 'id',
                title: 'name',
              }"
            ></a-tree-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="基本单位：">
            <a-select v-model="currForm.list.basicUnitId">
              <a-option
                v-for="item in unitData"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料属性">
            <a-select v-model="currForm.list.attribute">
              <a-option :value="1">自制</a-option>
              <a-option :value="2">委外</a-option>
              <a-option :value="3">虚拟</a-option>
              <a-option :value="4">采购</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-col :span="24">
        <a-form-item label="包装单位：">
          <a-space direction="vertical" fill>
            <a-table
              :pagination="false"
              :data="packagesData"
              :bordered="{ cell: true }"
            >
              <template #columns>
                <a-table-column title="包装编号" :width="180" align="center">
                  <template #cell="{ record }"
                    ><a-input v-model="record.name" allow-clear /></template
                ></a-table-column>
                <a-table-column title="包装单位" :width="180" align="center">
                  <template #cell="{ record }">
                    <a-select v-model="record.unitId">
                      <a-option
                        v-for="item in unitData"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.name }}</a-option
                      >
                    </a-select></template
                  ></a-table-column
                >

                <a-table-column title="换算方式" :width="180" align="center">
                  <template #cell>
                    <div>与基本单位进行换算 </div></template
                  ></a-table-column
                >
                <a-table-column title="换算率" :width="180" align="center">
                  <template #cell="{ record }"
                    ><a-input-number
                      :min="1"
                      v-model="record.conversionRate"
                      allow-clear /></template
                ></a-table-column>
                <a-table-column title="换算说明" :width="180" align="center">
                  <template #cell="{ record }"
                    ><div
                      v-show="
                        !record.conversionRate || !currForm.list.basicUnitId
                      "
                      ><span>-</span></div
                    ><div
                      v-show="
                        record.conversionRate && currForm.list.basicUnitId
                      "
                      ><span>1</span><span>-</span
                      ><span>{{ record.conversionRate }}</span></div
                    ></template
                  ></a-table-column
                >
                <a-table-column title="操作" :width="100" align="center">
                  <template #cell="{ rowIndex }">
                    <a-tooltip v-if="rowIndex > 0" content="删除">
                      <a-popconfirm
                        content="确认删除？"
                        type="error"
                        @ok="del(rowIndex)"
                      >
                        <IconFont
                          type="icon-delete"
                          :size="26"
                          :style="{
                            cursor: 'pointer',
                          }"
                        />
                      </a-popconfirm> </a-tooltip
                    ><span v-else> -- </span></template
                  ></a-table-column
                >
              </template>
            </a-table>
            <a-button type="text" @click="addPackages">新增</a-button>
          </a-space>
        </a-form-item></a-col
      >

      <a-form-item label="是否启用：">
        <a-radio-group v-model="currForm.list.enable" :default-value="1">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="2">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="启用安全库存：">
            <a-radio-group
              v-model="currForm.list.safetyStockState"
              :default-value="1"
            >
              <a-radio :value="1">是</a-radio>
              <a-radio :value="2">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="currForm.list.safetyStockState === 1" :span="12">
          <a-form-item label="安全库存：">
            <a-input-number
              :min="1"
              v-model="currForm.list.safetyStock"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="备注：">
        <a-textarea
          show-word-limit
          :max-length="300"
          :auto-size="{
            minRows: 5,
          }"
          v-model="currForm.list.remark"
        ></a-textarea>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch } from 'vue';
  import { cloneDeep } from 'lodash';
  import {
    GetClassificationList,
    GetUnitList,
    getMaterialUnitAll,
  } from '@/api/inventory-management/material-management';

  const unitData = ref();
  const getMaterialUnitData = async () => {
    const res = await getMaterialUnitAll();
    unitData.value = res;
  };
  getMaterialUnitData();
  const props = withDefaults(
    defineProps<{
      visible: boolean; // 是否显示对话框
      form?: any; // 传进来的数据
    }>(),
    {
      form: undefined,
      visible: false,
    }
  );

  const emit = defineEmits(['update:visible', 'materialEmit']);

  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  const packagesData = ref([
    { unitId: undefined, name: '', conversionRate: undefined, key: 1 },
  ]);

  const del = (index: number) => {
    packagesData.value.splice(index, 1);
  };

  const addPackages = () => {
    let newKey = packagesData.value.length + 1;
    packagesData.value.push({
      unitId: undefined,
      name: '',
      conversionRate: undefined,
      key: newKey,
    });
  };

  const currForm = reactive<any>({
    list: {
      number: '', // 物料编码
      name: '', // 物料名称
      spec: '', // 型号
      remark: '', // 备注
      materialId: undefined, // 物料分类id
      enable: 1, // 是否启用 1启用 2不启用
      measureType: 1, // measureType 1单计量 2多计量
      singleUnitId: undefined, // 单计量单位
      multiGroupId: undefined, // 多计量单位
      saleUnitID: undefined, // 销售单位id
      purchaseUnitID: undefined, // 采购单位id
      stockUnitID: undefined, // 库存单位id
      shipUnitID: undefined, // 发货单位id
      outputUnitID: undefined, // 生产单位id
      basicUnitId: undefined, //基本单位id
      attribute: undefined,
      safetyStockState: 1,
      safetyStock: undefined,
    },
  });

  let classficationList: any = ref([]); // 储存物料分类数据
  let singleList: any = ref([]); // 储存单计量数据
  let mutilList: any = ref([]); // 储存多计量数据
  let mutliChildList: any = ref([]); // 储存对应多计量的子数据

  let currParentName = ref(''); // 如果是多计量，储存当前父单位的值

  // 获取物料分类数据和单位数据
  const getData = async () => {
    try {
      const res = await Promise.all([
        // 获取物料分类数据
        GetClassificationList({}),
        // 获取单计量数据
        GetUnitList({
          page: 0,
          size: -1,
          type: 1,
        }),
        // 获取多计量数据
        GetUnitList({
          page: 0,
          size: -1,
          type: 2,
        }),
      ]);
      classficationList.value = res[0];
      singleList.value = res[1].content;
      mutilList.value = res[2].content;
    } catch (error: unknown) {
      console.log(error);
    }
  };

  watch(modalVisible, (newVal, oldVal) => {
    // 如果newVal为true
    if (newVal) {
      getData();
      currForm.list = {
        number: '', // 物料编码
        name: '', // 物料名称
        spec: '', // 型号
        remark: '', // 备注
        materialId: undefined, // 物料分类id
        enable: 1, // 是否启用 1启用 2不启用
        measureType: 1, // measureType 1单计量 2多计量
        singleUnitId: undefined, // 单计量单位
        multiGroupId: undefined, // 多计量单位
        saleUnitID: undefined, // 销售单位id
        purchaseUnitID: undefined, // 采购单位id
        stockUnitID: undefined, // 库存单位id
        shipUnitID: undefined, // 发货单位id
        outputUnitID: undefined, // 生产单位id
        basicUnitId: undefined, //基本单位id
      };
      packagesData.value = [
        {
          unitId: undefined,
          name: '',
          conversionRate: undefined,
          key: 1,
        },
      ];
    }
  });

  // 过滤物料分类数据
  const filterClassficationData = (searchValue: string, nodeData: any) => {
    return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
  };

  // 改变单计量或者多计量时的事件
  const changeUnitType = (val: number) => {
    // 如果从多计量改成单计量，计量相关的id全部清空， 反之一样
    if (val === 1) {
      currForm.list.multiGroupId = undefined;
      currForm.list.saleUnitID = undefined;
      currForm.list.purchaseUnitID = undefined;
      currForm.list.stockUnitID = undefined;
      currForm.list.shipUnitID = undefined;
      currForm.list.outputUnitID = undefined;
      currParentName.value = '';
    } else {
      currForm.list.singleUnitId = undefined;
    }
  };

  // 选择计量单位组时的事件
  const changeMultiGroup = (id: number) => {
    // 每次重新选择多计量单位先清空所有的子单位
    currForm.list.saleUnitID = undefined;
    currForm.list.purchaseUnitID = undefined;
    currForm.list.stockUnitID = undefined;
    currForm.list.shipUnitID = undefined;
    currForm.list.outputUnitID = undefined;

    // 根据下拉框获取父单位的name和对应子数据的值
    const temp = mutilList.value.find((item: any) => item.id === id);
    currParentName.value = temp.name;
    mutliChildList.value = temp.item;
  };

  // 保存
  const handleOk = () => {
    if (packagesData.value[0].unitId !== undefined) {
      currForm.list.packages = packagesData.value;
    }
    emit('materialEmit', currForm.list);
    modalVisible.value = false;
  };

  // 取消
  const handleCancel = () => {
    modalVisible.value = false;
    currForm.list = {
      number: '', // 物料编码
      name: '', // 物料名称
      spec: '', // 型号
      remark: '', // 备注
      materialId: undefined, // 物料分类id
      enable: 1, // 是否启用 1启用 2不启用
      measureType: 1, // measureType 1单计量 2多计量
      singleUnitId: undefined, // 单计量单位
      multiGroupId: undefined, // 多计量单位
      saleUnitID: undefined, // 销售单位id
      purchaseUnitID: undefined, // 采购单位id
      stockUnitID: undefined, // 库存单位id
      shipUnitID: undefined, // 发货单位id
      outputUnitID: undefined, // 生产单位id
    };
  };
</script>

<style scoped lang="less">
  .unchecked-radio {
    background-color: #fff;
    color: #dcdfe6;
    border: 1px solid #dcdfe6;
    font-weight: 700;
    font-size: 16px;
    position: relative;
    top: -10px;
  }
  .checked-radio {
    background-color: #3491fa;
    color: #fff;
    border: 1px solid #3491fa;
    font-weight: 700;
    font-size: 16px;
    position: relative;
    top: -10px;
  }
  .radio-icon-box-checked {
    border: 1px solid #3491fa;
    background-color: #fff;
  }
  .radio-icon-box-unchecked {
    border: 1px solid rgba(220, 223, 230, 1);
  }
  .radio-icon-checked {
    color: #3491fa;
  }

  .radio-icon-unchecked {
  }
  .radio-icon {
    position: relative;
    top: 3px;
  }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
    // font-size: 13px;
  }
</style>
